package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.common.BeanCopier;
import com.mk.common.Config;
import com.mk.common.FileUploadUtil;
import com.mk.common.FileUtils;
import com.mk.log.annotation.Log;
import com.mk.mapper.FileInfoMapper;
import com.mk.model.entity.FileInfo;
import com.mk.model.request.FileInfoRequest;
import com.mk.service.IFileInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 11:28 AM 3/16/18
 */
@Service
public class FileInfoService extends BaseService<FileInfoMapper,FileInfo> implements IFileInfoService {

    @Value("${location.fileupload.path}")
    private String FILE_UPLOAD_PATH;

    @Override
    @Transactional
    @Log(module = "文件管理",description = "添加文件")
    public Boolean saveFile(FileInfoRequest request) {
        if(ObjectUtils.isEmpty(request))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"上传的文件信息不可为空");
        if(request.getFile() == null || request.getDirId() == null || request.getPacId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"上传文件时未选择文件或未选定文件所在的文件夹");
        MultipartFile file = request.getFile();
        String url = FileUploadUtil.uploadFile(file,FILE_UPLOAD_PATH);
        FileInfo fileInfo = BeanCopier.copy(request,FileInfo.class);
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setPname(url);
        fileInfo.setSize(new Long(file.getSize()).intValue() / 1024);
        Date nowDate = new Date();
        fileInfo.setCreateTime(nowDate);
        fileInfo.setUpdateTime(nowDate);
        return super.insert(fileInfo);
    }

    @Override
    @Transactional
    @Log(module = "文件管理",description = "编辑文件信息")
    public Boolean updateFile(FileInfoRequest request) {
        if(request == null || request.getId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择需要编辑的文件信息");
        FileInfo exist = get(request.getId());
        if(exist == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"编辑的文件信息不存在");
        exist = BeanCopier.copy(request,FileInfo.class);
        exist.setUpdateTime(new Date());
        return super.updateById(exist);
    }

    @Override
    @Transactional
    public Boolean updateSnum(Long id) {
        FileInfo fileInfo = get(id);
        if(fileInfo == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"编辑的文件不存在");
        fileInfo.setSnum(fileInfo.getSnum() + 1);
        fileInfo.setUpdateTime(new Date());
        return super.updateById(fileInfo);
    }

    @Override
    @Transactional
    public Boolean updateDnum(Long id) {
        FileInfo fileInfo = get(id);
        if(fileInfo == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"编辑的文件不存在");
        fileInfo.setDnum(fileInfo.getDnum() + 1);
        fileInfo.setUpdateTime(new Date());
        return super.updateById(fileInfo);
    }

    @Override
    @Transactional
    @Log(module = "文件管理",description = "删除文件")
    public Boolean deleteFile(Long id) {
        if(id == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择删除的文件信息");
        FileInfo fileInfo = get(id);
        if(fileInfo == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除的文件信息不存在");
        fileInfo.setUpdateTime(new Date());
        fileInfo.setIsDeleted(Config.ABLE_CONFIG.UNABLE);
        if(super.updateById(fileInfo))
            return FileUtils.deleteFile(FILE_UPLOAD_PATH + fileInfo.getPname());
        else
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除文件信息失败");
    }

    @Override
    @Transactional
    @Log(module = "文件管理",description = "添加文件")
    public Boolean saveOnlyOne(FileInfoRequest request) {
        if(request == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"添加文件信息不可为空");
        if(StringUtils.isEmpty(request.getName()) || request.getDirId() == null
                || request.getPacId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"添加文件信息时文件名、对应的文件夹及包信息不可为空");
        FileInfo fileInfo = BeanCopier.copy(request,FileInfo.class);
        Date nowDate = new Date();
        fileInfo.setCreateTime(nowDate);
        fileInfo.setUpdateTime(nowDate);
        return super.insert(fileInfo);
    }

    @Override
    @Transactional
    @Log(module = "文件管理",description = "删除资料包下的所有文件")
    public Boolean delAllFilesByPacId(Long dirId, Long pacId) {
        List<FileInfo> fileInfos = findByDirId(dirId,pacId);
        int len = fileInfos.size();
        int slen = 0;
        if(!CollectionUtils.isEmpty(fileInfos)){
            for (FileInfo fileInfo : fileInfos) {
                if(deleteFile(fileInfo.getId()))
                    slen++;
            }
        }
        return len == slen;
    }

    @Override
    public FileInfo get(Long id) {
        return super.selectById(id);
    }

    @Override
    public List<FileInfo> findByDirId(Long dirId, Long pacId) {
        return super.selectList(new EntityWrapper<FileInfo>()
                .eq("dir_id",dirId)
                .eq("pac_id",pacId)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
    }

    @Override
    public List<FileInfo> keySearch(String key) {
        return super.selectList(new EntityWrapper<FileInfo>()
                .like("name",key)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
    }
}
